import React, { useEffect, useState } from 'react';
import { Col, Divider, Row, Spin, message } from 'antd';
import { connect, history } from 'umi';
import { getKeyRouter } from '@/utils';

import '../common/style.less';

import {
  JHXD_STATE,
  KCBSH_STATE,
  SHZ_STATE,
  XQBZ_STATE,
  XQZF_STATE,
  ZRBGH_STATE,
  purchaseNeedBusinessCategory,
  purchaseNeedCategory,
  purchaseNeedController,
  purchaseNeedOrderType,
} from '../common/Format';

import UpdateNeedCardBaseInfo from './UpdateNeedCardBaseInfo';
import UpdateNeedMaterial from './UpdateNeedMaterial';
import UpdateNeedMaterialModal from './UpdateNeedMaterialModal';
import { NeedUpdateContext } from '../common/NeedContext';
import { IActionEnum, useNeedUpdateReducer } from '../common/NeedReducer';
import { useNeedUpdate } from '../common/useNeedUpdate';
import { useDictionary } from '../common/useDictionary';
import { UpdateAddEngIneerModal } from './UpdateAddEngIneerModal';
import { NeedUpdateAPI } from '../common/type';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import MaterialDetailDrawer from '../../Acomponents/MaterialDetailDrawer';

import { WorkflowChedkRecord, WorkflowNoDefaultTable, WorkflowSwitchModal, WorkflowCheckModal } from '@/components/WorkflowCommonCopy';
import { addPlanServices, syncPDFtoOAServices } from '../services/UpdateService';
const prefixCls = 'need-update';

const UpdateView: React.FC<NeedUpdateAPI.INeedUpdateView> = ({ locationProps, curRes }) => {
  const { dispatch, materialList, dataSource, BottomDataSource } = useNeedUpdateReducer();
  const { materialTypeList, cancelTypeList } = useDictionary();
  const { needInfo, needTitle, submit, change, isShowState, loading, materialOperation, tableForm, isView } = useNeedUpdate({
    locationProps,
    materialList,
    dispatch,
  });

  const {
    onChangeMaterialModalState,
    onChangeCancelModalState,
    onChangeAuditRecordDrawerState,
    onChangeMaterialDetailDrawerState,
    onChangeWorkFlowInfoObj,
    setShowSwitchFlow,
    closeSwitchFlowModal,
    onChangeWorkflowCheck,
    reloadInfoFunc,
  } = change;

  const { workFlowInfoObj, showSwitchFlow, isShowWorkflowCheck, nodesFlowListMemo } = isShowState;
  const [pageRouterDomID, _setPageRouterDomID] = useState<string>(`needUpdateView-imageBox-${getKeyRouter()}`);
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [flag, setFlag] = useState(false);

  /**添加工程服务物料的弹窗*/
  const [isShowAddEngIneer, setIsShowAddEngIneer] = useState<boolean>(false);

  const onChangeWorkRecord = () => setIsShowWorkRecord(!isShowWorkRecord);

  /**当状态是主任办公会审议，审核状态是审核中的时候，需要跳转到同步页面去*/
  useEffect(() => {
    if (needInfo?.state == ZRBGH_STATE()) {
      history.push({
        pathname: `/purchaseNeedMaterialController/dataGrid/{params}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          info: needInfo,
          delRouterName: history.location.pathname, //必传,要删除的路由名称
          returnPathName: locationProps?.state?.returnPathName,
        },
      });
    }
  }, [needInfo?.state, needInfo?.checkState]);

  /** 同步审核记录给档案 */
  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices((res) => {});

  /** 添加计划serivces */
  const { addPlanRun, addPlanLoading } = addPlanServices((res: Record<string, any>) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
    }
  });

  const syncPDFtoOARunfun = (infoObj) => {
    //需要调用同步接口
    let mactivitiHisTaskInstList = infoObj?.paramObject?.[purchaseNeedCategory()]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
    let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
    syncPDFtoOARun(resObj);
  };

  /**
   * 监听状态，执行计划下达和同步档案
   * */
  useEffect(() => {
    if (needInfo?.state == KCBSH_STATE() || needInfo?.state == SHZ_STATE()) {
      setFlag(true);
    }
    if (needInfo?.state == JHXD_STATE()) {
      if (!needInfo?.purchasePlan?.id && flag) {
        /** 计算通过的物料总价 */
        let allExpectSum = 0;
        needInfo?.purchaseNeedMaterials?.forEach((item) => {
          if (item?.checkState == 1) {
            allExpectSum += Number(item?.expectSum);
          }
        });

        /** 调添加到计划的接口 */
        let addPlanData = {
          // <<<====================申请单信息====================>>>
          supplyWay: needInfo?.supplyWay,
          supplyKind: needInfo?.supplyKind,
          planName: needInfo?.needName,
          planInfo: needInfo?.needInfo,
          expectSum: allExpectSum,
          state: '0',
          // <<<====================人员操作信息====================>>>
          applyCompanyID: needInfo?.applyCompanyID,
          applyCompanyName: needInfo?.applyCompanyName,
          applyDepartmentID: needInfo?.applyDepartmentID,
          applyDepartmentName: needInfo?.applyDepartmentName,
          applyPositionID: needInfo?.applyPositionID,
          applyPositionName: needInfo?.applyPositionName,
          applyerID: needInfo?.applyerID,
          applyerName: needInfo?.applyerName,
          applyTime: needInfo?.applyTime,
          ownCompanyID: needInfo?.ownCompanyID,
          ownCompanyName: needInfo?.ownCompanyName,
          ownDepartmentID: needInfo?.ownDepartmentID,
          ownDepartmentName: needInfo?.ownDepartmentName,
          ownPhone: needInfo?.ownPhone, // 联系电话
          ownPositionID: needInfo?.ownPositionID,
          ownPositionName: needInfo?.ownPositionName,
          ownTime: needInfo?.ownTime,
          ownerID: needInfo?.ownerID,
          ownerName: needInfo?.ownerName, // 联系人
          // <<<====================申请物料信息====================>>>
          mpurchaseNeeds: [{ id: needInfo?.id }],
          purchaseNeedMaterials: needInfo?.purchaseNeedMaterials?.map((item) => {
            return { id: item?.id };
          }),
        };

        addPlanRun(addPlanData);
        syncPDFtoOARunfun(needInfo);
      }
    }
  }, [needInfo?.state, flag]);

  return (
    <NeedUpdateContext.Provider
      value={{
        isView,
        prefixCls,
        needInfo,
        cancelTypeList,
        materialTypeList,
        materialList,
        dispatch,
        pageRouterDomID,
        tableForm: {},
        nodesFlowListMemo,
        dataSource,
        BottomDataSource,
        reloadInfoFunc,
        curRes,
        locationState: locationProps?.state,
      }}
    >
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
          width: '100%',
          overflow: 'hidden',
        }}
      >
        <div className={prefixCls} style={{ flex: 'auto', overflow: 'hidden' }}>
          <Spin spinning={loading || addPlanLoading || syncPDFtoOALoading}>
            {/* card - 盒子外层 */}
            <UpdateNeedCardBaseInfo
              onSubmit={submit.baseInfoSubmit}
              onExport={submit.exportSubmit}
              onCancel={onChangeCancelModalState}
              openModal={onChangeMaterialModalState}
              openDrawer={onChangeAuditRecordDrawerState}
              setIsShowWorkRecord={onChangeWorkRecord}
              onChangeWorkflowCheck={onChangeWorkflowCheck}
              curRes={curRes}
            >
              {/* body - 标题 */}
              <Divider style={{ fontSize: '1.3rem', margin: '0.8rem 0' }}>
                {typeof needInfo?.id == 'undefined' ? needTitle : needInfo?.needName ?? needTitle}
              </Divider>

              {/* table - 需求物料的表格 */}
              <UpdateNeedMaterial
                openDrawer={onChangeMaterialDetailDrawerState}
                openModal={onChangeMaterialModalState}
                openAddEngIneer={() => setIsShowAddEngIneer(true)}
                onSave={materialOperation.saveNeedAndMaterialParam}
                tableForm={tableForm}
              />

              {/* drawer - 物料详情右侧抽屉 */}
              <MaterialDetailDrawer
                isShowDetail={isShowState.isShowMaterialDetail.isShow}
                materialId={isShowState.isShowMaterialDetail.id}
                pageRouterDomID={pageRouterDomID}
                onClose={() => {
                  onChangeMaterialDetailDrawerState({
                    id: '',
                    isShow: false,
                  });
                }}
              />
            </UpdateNeedCardBaseInfo>
          </Spin>
        </div>

        {/* 选择物料弹窗 */}
        {isShowState.isShowMaterial && <UpdateNeedMaterialModal onClose={onChangeMaterialModalState} onSave={materialOperation.saveMaterial} />}

        {/* 添加工程服务弹窗 */}
        {isShowAddEngIneer && (
          <UpdateAddEngIneerModal
            onClose={() => setIsShowAddEngIneer(false)}
            onSave={(res) => {
              let newarr = [...materialList, { ...res }];
              dispatch({
                type: IActionEnum.UPDATE_MATERIAL_LIST,
                payload: newarr,
              });
            }}
          />
        )}

        {/* 撤销 */}
        {/* {isShowState.isShowCancel && (
          <RevokeModal
            resObj={needInfo}
            revokeRequestUrl={'/purchaseNeedController/invalid'}
            onClose={() => onChangeCancelModalState(false)}
            reqBody={{ state: XQBZ_STATE() }}
            modalTip={
              <div style={{ color: '#000' }}>
                确认是否撤销【<span style={{ color: 'red' }}>{needInfo?.needName}</span>】的审核, 撤销后可重新提交！
              </div>
            }
            reloadRequest={() => {
              history.push({
                // 新增编辑页
                pathname: `/purchaseNeedController/edit/:${getKeyRouter()}${getKeyRouter()}`,
                state: {
                  info: needInfo,
                  isView: false,
                  delRouterName: history.location.pathname,
                },
              });
            }}
          />
        )} */}

        {/* 审核记录 */}
        {needInfo?.paramObject?.[purchaseNeedCategory()] && (
          <Row style={{ margin: 0 }}>
            <Col span={24}>
              <WorkflowChedkRecord
                curRes={curRes}
                dataDetailInfo={needInfo}
                flowBusinessType={purchaseNeedCategory()}
                requestController={purchaseNeedController}
                reloadPageCallback={reloadInfoFunc}
                revokeStateID={XQBZ_STATE()}
                allBtnFuncQuqry={isShowState?.workflowPowerAllBtn}
                tabPaneHeight={0.35}
                isCheckDrawer={JHXD_STATE() == '5' ? false : true}
                isShowCollapse={isShowWorkRecord}
                changeCollapse={(val) => setIsShowWorkRecord(val)}
                cancelStateId={XQZF_STATE()}
              />
            </Col>
          </Row>
        )}

        {/* 发起流程审批 */}
        {workFlowInfoObj?.showWorkFlowModal && (
          <WorkflowSwitchModal
            openVisible={workFlowInfoObj?.showWorkFlowModal}
            businessInfoObj={workFlowInfoObj?.selectFlowRows}
            requestController={purchaseNeedController}
            orderType={workFlowInfoObj?.selectFlowRows?.orderType || purchaseNeedOrderType()}
            category={purchaseNeedCategory()}
            businessCategory={purchaseNeedBusinessCategory()}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
            reloadInfoCallback={() => {
              // 跳转详情页
              history.push({
                pathname: `/purchaseNeedController/getPurchaseNeedByID/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
                state: {
                  info: needInfo,
                  isView: true,
                  returnPathName: locationProps?.state?.returnPathName,
                  delRouterName: history.location.pathname,
                },
              });
            }}
            openFlowChangeModal={setShowSwitchFlow}
            onClose={() => {
              onChangeWorkFlowInfoObj({
                ...workFlowInfoObj,
                showWorkFlowModal: false,
              });
            }}
            replaceStrObj={{ own: 'apply', workflowType: 'category' }}
          />
        )}

        {/* 审批弹窗 */}
        {isShowWorkflowCheck?.isShow && (
          <WorkflowCheckModal
            detailInfoObj={needInfo?.paramObject?.[purchaseNeedCategory()]?.mactivitiTaskList?.[0]}
            flowBusinessType={purchaseNeedCategory()}
            requestController={purchaseNeedController}
            clickBtnText={isShowWorkflowCheck?.resObj}
            reloadCallback={reloadInfoFunc}
            onClose={() => {
              onChangeWorkflowCheck({
                isShow: false,
                resObj: null,
              });
            }}
          />
        )}

        {/* 挑选流程组件 */}
        {showSwitchFlow && (
          <WorkflowNoDefaultTable
            openVisibleSwitch={showSwitchFlow}
            onCloseSwitch={closeSwitchFlowModal}
            requestController={purchaseNeedController}
            orderType={workFlowInfoObj?.selectFlowRows?.orderType || purchaseNeedOrderType()}
            category={purchaseNeedCategory()}
            businessCategory={purchaseNeedBusinessCategory()}
            saveSelectFlowID={(flowId: string) => {
              onChangeWorkFlowInfoObj({
                ...workFlowInfoObj,
                saveNoDefaultFlowID: flowId,
              });
            }}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
          />
        )}
      </div>
    </NeedUpdateContext.Provider>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(UpdateView);
